package com.example.exercise.task;

import com.example.exercise.common.annotation.LogForTask;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 定时任务执行类，具体的业务实现可以用依赖注入的方式
 */
@Component
public class DemoSchedule {

    @LogForTask(description = "方法执行时长超过30秒就打印日志",milliseconds = 3000)
    @Scheduled(fixedRate = 30)//30秒执行一次
    @Async
    public void logWriteDemo1(){
        System.out.println("30秒执行一次");
        try {
            Thread.sleep(new Random().nextInt(50000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @LogForTask(description = "方法执行时长超过120秒就打印日志",milliseconds = 10000)
    @Scheduled(fixedRate = 120)//10秒执行一次
    @Async
    public void logWriteDemo2(){
        System.out.println("120秒执行一次");
        try {
            Thread.sleep(new Random().nextInt(30000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @LogForTask(description = "方法执行时长超过3600秒就打印日志",milliseconds = 3600000)
    @Scheduled(cron = "0 30 2 * * ?")//每天凌晨2点30分0秒执行一次
    public void onceADayDemo(){
        System.err.println("每天凌晨2点30分0秒执行一次");
    }

    @LogForTask(description = "方法执行时长超过1800秒就打印日志",milliseconds = 1800000)
    @Scheduled(cron = "0 0/10 7-22 * * ?")//每天7点至22点每隔60分钟执行一次
    @Async
    public void runCirclePeriod(){
        System.err.println("每天7点至22点每隔60分钟执行一次");
    }
}
